<script setup lang="ts">
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { watch } from 'vue'
  import {
    useCheckReceivePayment,
    useGetReceivePaymentDetail,
    useGetReceivePaymentDetailOrderList,
  } from '@/services/pages/withdrawal/receive-payment/useReceivePayment'
  import { TableColumnCtx } from 'element-plus'
  import { useRouter } from 'vue-router'

  interface SummaryMethodProps {
    columns: TableColumnCtx<WithdrawalReceivePayment>[]
    data: WithdrawalReceivePayment[]
  }

  const { checkForm, checkLoading, check, resetForm } = useCheckReceivePayment()
  const { detail, getDetailLoading, getDetail } = useGetReceivePaymentDetail()
  const { orderList, getOrderListLoading, getOrderList } = useGetReceivePaymentDetailOrderList()

  const props = defineProps({
    receivePaymentId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 全局路由对象
  const router = useRouter()

  // 弹窗显示状态
  const visible = defineModel('modelValue', { type: Boolean, default: false })

  /**
   * 隐藏弹窗
   */
  const hideDialog = () => {
    visible.value = false
    resetForm()
  }

  /**
   * 确定事件
   */
  const onConfirm = async () => {
    const res = await check()
    if (res.code === 20000) {
      emits('update')
      hideDialog()
      HMessage.success('审核成功')
      return
    }
    HMessageBox.error(res.message)
  }

  /**
   * 获取合计
   * @param param - 参数
   */
  const getSummaries = (param: SummaryMethodProps) => {
    const result: Array<string> = []
    param.columns.forEach((column, index) => {
      // 服务费合计
      if (index === 2) {
        result[2] = `￥${orderList.value
          .map((item) => Number(item.serviceTotalFee))
          .reduce((prev, current) => prev + current, 0)
          .toFixed(2)}`
      }

      // 物料费合计
      if (index === 3) {
        result[3] = `￥${orderList.value
          .map((item) => Number(item.spareTotalFee))
          .reduce((prev, current) => prev + current, 0)
          .toFixed(2)}`
      }

      // 总费用
      if (index === 4) {
        let totalFee = 0
        orderList.value.forEach((item, index) => {
          totalFee += Number(calcRowTotalFee(index))
        })
        result[4] = `￥${totalFee.toFixed(2)}`
      }
    })
    return result
  }

  /**
   * 工单单号点击事件
   * @param {string} orderId - 工单id
   */
  const handleOrderNoClick = (orderId: string) => {
    visible.value = false
    router.push(`/order/odetail/${orderId}`)
  }

  /**
   * 计算某一行的总费用
   * @param {number} index - 行索引
   */
  const calcRowTotalFee = (index: number) => {
    const receiptPayment = orderList.value[index]
    const materialFee = receiptPayment.spareTotalFee || 0
    const serviceFee = receiptPayment.serviceTotalFee || 0
    const total = materialFee + serviceFee
    return Number((total || 0).toFixed(0)).toFixed(2)
  }

  watch(visible, (value) => {
    if (value && props.receivePaymentId) {
      checkForm.value.receivePaymentIds = [props.receivePaymentId]
      getDetail(props.receivePaymentId)
      getOrderList(props.receivePaymentId)
    }
  })
</script>

<template>
  <h-drawer
    v-model="visible"
    :width="1000"
    unit="px"
    :loading="checkLoading || getDetailLoading || getOrderListLoading"
    title="审核收款单"
    @close="hideDialog"
  >
    <div>
      <div class="title-priamry mb-6px">基本信息</div>
      <div class="inof-list">
        <div class="info-item company-name">
          <div class="label">客户名称：</div>
          <div class="value">{{ detail.username }}</div>
        </div>
        <div class="info-item company-phone">
          <div class="label">公司手机号：</div>
          <div class="value">{{ detail.userPhone }}</div>
        </div>
        <div class="info-item">
          <div class="label">审核备注：</div>
          <div class="value">
            <!-- <el-form :model="checkForm" inline-message class="modal_form_content" label-position="top">
            <el-form-item label="审核备注"> -->
            <el-input
              v-model="checkForm.remark"
              type="textarea"
              maxlength="100"
              placeholder="请输入审核备注"
              show-word-limit
              resize="both"
            />
            <!-- </el-form-item>
            </el-form> -->
          </div>
        </div>
      </div>

      <div class="table">
        <div class="title-priamry mb-6px">关联工单</div>
        <el-table :data="orderList" :border="true" :summary-method="getSummaries" show-summary>
          <!-- 序号 -->
          <el-table-column type="index" width="50" :align="'center'" fixed="left" label="序号" />

          <!-- 工单单号 -->
          <el-table-column width="140" show-overflow-tooltip prop="workNo" label="工单单号">
            <template #default="{ row }">
              <h-link @click="handleOrderNoClick(row.workId)">{{ row.workNo }}</h-link>
            </template>
          </el-table-column>

          <!-- 服务费 -->
          <el-table-column width="80" label="服务费">
            <template #default="{ row }">
              ￥{{ (Number(row['serviceTotalFee']) || 0).toFixed(2) }}
            </template>
          </el-table-column>

          <!-- 物料费 -->
          <el-table-column width="100" label="物料费">
            <template #default="{ row }">
              ￥{{ (Number(row['spareTotalFee']) || 0).toFixed(2) }}
            </template>
          </el-table-column>

          <!-- 总费用 -->
          <el-table-column width="100" label="总费用">
            <template #default="{ $index }"> ￥{{ calcRowTotalFee($index) }} </template>
          </el-table-column>

          <!-- 开票类型 -->
          <el-table-column width="120" label="开票类型">
            <template #defualt="{ row }">
              {{ row.ticketType === 1 ? '增值税普通发票' : '增值税专用发票' }}
            </template>
          </el-table-column>

          <!-- 抬头类型 -->
          <el-table-column width="120" label="抬头类型">
            <template #defualt="{ row }">
              {{ row.headType === 1 ? '企业' : '个人' }}
            </template>
          </el-table-column>

          <!-- 发票抬头 -->
          <el-table-column width="120" show-overflow-tooltip prop="header" label="发票抬头" />

          <!-- 发票状态 -->
          <el-table-column width="100" label="发票状态">
            <template #default="{ row }">
              <h-status v-if="row.openTicket">已申请开票</h-status>
              <h-status v-else type="warning">未申请开票</h-status>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <h-button type="primary" is-modal @click="onConfirm">审核通过</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .modal_form_content {
    padding-left: 0;
    padding-right: 0;
  }

  .table {
    margin-top: 24px;
  }

  .inof-list {
    display: flex;
    column-gap: 36px;

    .info-item {
      display: flex;
      align-items: flex-start;

      .label {
        color: #606266;
        white-space: nowrap;
        height: 28px;
        line-height: 28px;
      }
    }

    .company-name {
      .value {
        max-width: 250px;
        min-height: 28px;
        display: flex;
        align-items: center;
      }
    }

    .company-phone {
      .value {
        height: 28px;
        line-height: 28px;
      }
    }

    :deep(.el-textarea__inner) {
      width: 300px !important;
      height: 28px;
      min-height: 28px !important;
      max-height: 100px !important;
    }
  }
</style>
